"use strict";

function rand_range(min, max) {
	return Math.floor(Math.random() * (max - min + 1) + min);
}

function shuffle(deck) {
	var i, temp, deck_size, new_slot;
	deck_size = deck.length;
	for (i = 0; i < deck_size - 1; ++i) {
		temp = deck[i];
		new_slot = rand_range(i + 1, deck_size - 1);
		deck[i] = deck[new_slot];
		deck[new_slot] = temp;
	}	
}

var hangoutModule = angular.module('HangoutModule', []);
hangoutModule.factory('hangoutApi', function() {
	var hangoutApiInstance = function(scope) {
		gapi.hangout.data.onStateChanged.add(function(stateChangeEvent) {
			console.log("in handler");
			try {
				scope.hangoutStateHandler(stateChangeEvent.state, stateChangeEvent.metadata);
			} catch (err) {
				console.log(err);
			}
		});
	}
	return hangoutApiInstance; 
});

function DeckController($scope, hangoutModule) {
	var DECK_SIZE = 50;
	$scope.deck = [];
	$scope.dealt_cards = [];
	var i = 0;
	for (i = 0; i < DECK_SIZE; ++i) {
		$scope.deck.push(i);
	}
	shuffle($scope.deck);
	$scope.deals_so_far = 0;

	$scope.hangoutStateHandler = function(state, metadata) {
		console.log("DeckController.hangoutStateHandler");
		console.log(state);
		if ("deal_count" in state) {
			console.log("deal_count in state: " + state["deal_count"]);
			$scope.deals_so_far = parseInt(state["deal_count"]);
		}
	}
	hangoutModule($scope);

	$scope.deal = function() {
		if (deck.length == 0) return;
		$scope.dealt_cards.push($scope.deck.pop());
		var new_val = $scope.deals_so_far + 1 + "";
		console.log("setting deal_count to " + new_val);
		gapi.hangout.data.setValue("deal_count", new_val);
	}
	
	$scope.returnToBottom = function(card) {
		$scope.removeFromDealt(card);
		$scope.deck.splice(0,0,card);
	}
	
	$scope.keep = function(card) {
		$scope.removeFromDealt(card);
	}
	
	$scope.removeFromDealt = function (card) {
		var i = 0;
		for (i = 0; i < $scope.dealt_cards.length; ++i) {
			if ($scope.dealt_cards[i] === card) {
				$scope.dealt_cards.splice(i, 1);
				return;
			}
		}
	}
}

DeckController.$inject = ['$scope', 'hangoutApi'];
